package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.*;
import com.leyou.pojo.PageResult;
import com.leyou.utils.ThreadUtils;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 岩冰
 * @version 1.0
 * @date:2018/9/29
 */
@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final Logger logger = LoggerFactory.getLogger(GoodsService.class);
    public PageResult<SpuBo> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        //先查到spu对应的数据
        PageHelper.startPage(page, rows);
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        Page<Spu> pageInfo = (Page<Spu>) spuMapper.selectByExample(example);
        //将spu对象封装
        List<SpuBo> spuBos = pageInfo.stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu, spuBo);
            //查询brand的名称
            Brand brand = brandService.queryByBrandId(spu.getBrandId());
            spuBo.setBname(brand.getName());
            //查询分类的名称
            List<String> cnames = categoryService.queryCategoryNames(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(String.join("/", cnames));
            return spuBo;
        }).collect(Collectors.toList());
        return new PageResult<>(pageInfo.getTotal(), spuBos);
    }

    @Transactional
    public void saveGoods(SpuBo spuBo) {
        //添加spuBo的属性
        spuBo.setLastUpdateTime(new Date());
        spuBo.setSaleable(true);
        spuBo.setCreateTime(spuBo.getLastUpdateTime());
        spuBo.setValid(true);
        spuMapper.insert(spuBo);
        //添加detail
        spuDetailMapper.insert(spuBo.getSpuDetail().setSpuId(spuBo.getId()));
        //添加商品sku性息
        spuBo.getSkus().forEach(sku -> {
            sku.setSpuId(spuBo.getId()).setCreateTime(
                    spuBo.getLastUpdateTime()).setLastUpdateTime(spuBo.getLastUpdateTime());
            skuMapper.insert(sku);
            //添加stock信息
            stockMapper.insert(new Stock().setSkuId(sku.getId()).setStock(sku.getStock()));

        });
            this.sendMessage(spuBo.getId(),"insert");
    }

    public SpuDetail querySpuDetailById(Long id) {

        return spuDetailMapper.selectByPrimaryKey(id);
    }

    public List<Sku> querySkuBySpuId(Long id) {

        //根据链式查询设置stock
        return skuMapper.select(new Sku().setSpuId(id)).stream().map(sku ->
                sku.setStock(stockMapper.selectByPrimaryKey(sku.getId()).getStock()))
                .collect(Collectors.toList());
    }

    public void update(SpuBo spuBo) {
        //1.先修改spu
        spuBo.setLastUpdateTime(new Date());
        spuMapper.updateByPrimaryKeySelective(spuBo);
        //2.修改spudetail
        spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());
        //3.修改sku

        //3.1-----先查出来spu对应以前的sku的信息
        List<Long> skuIds = skuMapper.select(new Sku().setSpuId(spuBo.getId())).stream().map(Sku::getId).collect(Collectors.toList());
        //先将spu对应的skus中新增的添加到文件中
        List<Sku> skuList = spuBo.getSkus();
        skuList.forEach(sku -> {
            sku.setLastUpdateTime(spuBo.getLastUpdateTime());
            if (sku.getId() == null) {
                sku.setCreateTime(spuBo.getLastUpdateTime()).setSpuId(spuBo.getId());
                skuMapper.insert(sku);
                Stock stock = new Stock().setSkuId(sku.getId()).setStock(sku.getStock());
                stockMapper.insert(stock);

            } else if ((!skuIds.isEmpty())&&skuIds.contains(sku.getId())){
                //修改,
                skuMapper.updateByPrimaryKeySelective(sku);
                //修改stock
                stockMapper.updateByPrimaryKeySelective(new Stock()
                        .setSkuId(sku.getId()).setStock(sku.getStock()));
                //为了对后面的修改enable的值进行操作,这儿对skuids进行删掉对应的id值
                skuIds.remove(sku.getId());
            }
            //剩余skuIds中对应的sku就应该是本次修改中需要失效的sku
            skuIds.forEach(skuId-> skuMapper.updateByPrimaryKeySelective(new Sku().setId(skuId).setEnable(false)));
        });
        this.sendMessage(spuBo.getId(),"update");
    }

    public void updateSpuSaleable(Long id) {
        Spu spu = this.spuMapper.selectByPrimaryKey(id);
        spuMapper.updateSpuSaleable(id);
        if (spu.getSaleable()) {
            //下架,需要删掉索影库
            sendMessage(id,"delete");
        }
    }

    public Spu querySpuBySpuId(Long id) {

        return this.spuMapper.selectByPrimaryKey(id);
    }
    private void sendMessage(Long id, String type){
        try {
            this.amqpTemplate.convertAndSend("item."+type,id);
        } catch (AmqpException e) {
            e.printStackTrace();
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }

    }
}
